package com.doge.service.admin.admin;

import com.alibaba.druid.util.StringUtils;
import com.doge.bean.base.BaseData;
import com.doge.bean.base.BaseParam;
import com.doge.bean.pojo.admin.Admin;
import com.doge.bean.pojo.admin.AdminExample;
import com.doge.exception.Delete502Exception;
import com.doge.exception.Param602Exception;
import com.doge.mapper.AdminMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @program: doge
 * @description:
 * @author: Keyu Li
 * @create: 2021-11-29 20:43
 **/

@Service
public class AdminServiceImpl implements AdminService{
    @Autowired
    AdminMapper mapper;

    @Override
    public BaseData list(BaseParam param, String username) {
        // 分页
        PageHelper.startPage(param.getPage(),param.getLimit());

        // 设置条件查询
        AdminExample example = new AdminExample();
        AdminExample.Criteria criteria = example.createCriteria().andDeletedEqualTo(false);
        // 如果 username不为空，则设置 criteria
        if (!StringUtils.isEmpty(username)){
            criteria.andUsernameLike("%"+username+"%");
        }
        // 设置sort,order
        example.setOrderByClause(param.getSort() + " " + param.getOrder());
        // 获取 admin 列表，设置typeHandler映射，把 String orderIds 映射为 数组
        List<Admin>  admins = mapper.selectByExample(example);
        // 获取 info, 并返回 BaseData
        PageInfo info = new PageInfo(admins);
        BaseData data = BaseData.list(admins, info.getTotal());
        data.setPage(param.getPage());
        data.setLimit(param.getLimit());
        data.setPages(info.getPages());
        return data;
    }

    @Override
    public void create(Admin admin, HttpServletRequest request) throws Exception {
        // 判断管理员名称是否重复
        AdminExample example = new AdminExample();
        example.createCriteria().andUsernameEqualTo(admin.getUsername());
        long l = mapper.countByExample(example);
        if (l!=0)
            throw new Param602Exception("管理员名称已存在！");
        // 添加时间
        admin.setAddTime(new Date());
        admin.setUpdateTime(new Date());
        admin.setDeleted(false);
        // 插入管理员，获得id
        mapper.insertSelective(admin);
        // 记录操作的用户名
        request.setAttribute("adminName",admin.getUsername());
    }

    @Override
    public void update(Admin admin, HttpServletRequest request) throws Exception {
        // 禁止修改 admin123,id=1
        if (admin.getId()==1){
            // 禁止修改 admin123 的用户名
            if (!"admin123".equals(admin.getUsername()))
                throw new Param602Exception("禁止修改admin123用户名！");
            // 禁止删除 admin123 的超级管理员权限
            if (!Arrays.stream(admin.getRoleIds()).anyMatch(x->x==1)){
                // 流式处理，判断是否存在超级管理员
                throw new Param602Exception("admin123必须包含超级管理员身份！");
            }
        }

        // 判断管理员是否已经存在(排除自身)
        AdminExample example = new AdminExample();
        example.createCriteria().andUsernameEqualTo(admin.getUsername()).andIdNotEqualTo(admin.getId());
        long l = mapper.countByExample(example);
        if (l!=0)
            throw new Param602Exception("管理员名称已存在！");
        // 更新 updateTime
        admin.setUpdateTime(new Date());
        // 更新用户: 只更新不为 null的列
        mapper.updateByPrimaryKeySelective(admin);
        // 记录操作的用户名
        request.setAttribute("adminName",admin.getUsername());
    }

    @Override
    public void delete(Admin admin, HttpServletRequest request) throws Exception {
        // 判断删除的是否是 id=1 或 admin123 用户
        if (admin.getId()==1)
            throw new Delete502Exception("禁止删除admin123！");
        // 根据 id和 username删除用户（缺一不可！）
        AdminExample example = new AdminExample();
        example.createCriteria().andUsernameEqualTo(admin.getUsername()).andIdEqualTo(admin.getId()).andDeletedEqualTo(false);
        // 逻辑删除，不是真实的删除
        admin.setDeleted(true);
        int i = mapper.updateByExampleSelective(admin,example);
        if (i!=1)
            throw new Delete502Exception("删除管理员失败！");
        // 记录操作的用户名
        request.setAttribute("adminName",admin.getUsername());
    }
}
